package com.fin.zw.intelligentbot.service;

import com.fin.zw.intelligentbot.entity.QUploadFile;
import com.fin.zw.intelligentbot.entity.UploadFile;
import com.fin.zw.intelligentbot.repository.UploadFileRepository;
import com.fin.zw.intelligentbot.util.Snowflake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.*;

@Service("uploadFileService")
public class UploadFileService {

    private static final Logger log = LoggerFactory.getLogger(UploadFileService.class);

    @Autowired
    private UploadFileRepository uploadFileRepository;

    @Value("${file.dir}")
    private String fileDir;

    @Autowired
    private Snowflake snowflake;

    public UploadFile findOne(String id) {
        UploadFile uploadFile = uploadFileRepository.findById(id).get();
        return uploadFile;
    }

    public File findOneFileById(String id){
        UploadFile uploadFile = uploadFileRepository.findById(id).get();
        File file = new File(fileDir + "/" + uploadFile.getFileName());
        return file;
    }

    public File findOneFileByName(String fileName) {
        QUploadFile qUploadFile = QUploadFile.uploadFile;
        UploadFile uploadFile = uploadFileRepository.findOne(qUploadFile.fileName.contains(fileName)).get();
        File file = new File(fileDir + "/" + uploadFile.getFileName());
        return file;
    }

    public ResponseEntity<UploadFile> fileUpload(MultipartFile file) throws IOException {

        UploadFile uploadFile = fileUpload(file.getInputStream(), file.getOriginalFilename());
        return ResponseEntity.ok().body(uploadFile);

    }

    public UploadFile fileUpload(InputStream inputStream, String originalName) throws IOException {
        String extensionName = originalName.substring(originalName.lastIndexOf(".") + 1);
        String fileId = String.valueOf(snowflake.next());
        String fileName = fileId + "." + extensionName;
        saveToDisk(inputStream, extensionName, fileId);
        UploadFile uploadFile = saveUploadFile(fileId, fileName, originalName, extensionName);
        inputStream.close();
        return uploadFile;

    }

    private void saveToDisk(InputStream inputStream, String extensionName, String fileId) throws IOException {
        File outFile = new File(fileDir);
        if (!outFile.exists()) {
            outFile.mkdirs();
        }
        String fileName = fileId + "." + extensionName;
        OutputStream ot = new FileOutputStream(fileDir + "/" + fileName);
        byte[] buffer = new byte[1024];
        int len;
        while ((-1 != (len = inputStream.read(buffer)))) {
            ot.write(buffer, 0, len);
        }
        ot.close();
    }

    private UploadFile saveUploadFile(String fileId, String fileName
            , String originalName, String extensionName) {
        UploadFile uploadFile = new UploadFile();
        uploadFile.setOriginalName(originalName);
        uploadFile.setExtensionName(extensionName);
        uploadFile.setFileName(fileName);
        uploadFile.setId(fileId);
        uploadFile.setUrl(fileName);
        return uploadFileRepository.save(uploadFile);
    }



    public List<UploadFile> getUploadFile(String fileIds) {
        List<UploadFile> uploadFileList = new ArrayList<>();
        if (fileIds != null && !fileIds.isEmpty()) {
            String[] ids = fileIds.split(",");
            for (int i = 0; i < ids.length; i++) {
                UploadFile uploadFile = findOne(ids[i].toString());
                uploadFileList.add(uploadFile);
            }
        }
        return uploadFileList;
    }
}
